package com.dk.nfc.DKCloudID;

import android.support.annotation.NonNull;
import android.util.Log;

import com.DKCloudID.crypt.MsgCrypt;
import com.dk.log.DKLog;
import com.dk.nfc.Tool.StringTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DKDeviceRegister {
    private static final String TAG = "DKDeviceRegister";
    private static final int TIME_OUT_MS = 20000;
    private String err_msg;

    /**
     * 激活设备，同步阻塞方式，请在子线程中运行
     * @param msgCrypt 加密实例
     * @param License 授权码，请询问供应商提供
     * @param deviceName 设备名称
     * @param key 密钥，请询问供应商提供
     * @return true - 成功， false - 失败
     */
    public boolean register(MsgCrypt msgCrypt, String License, String deviceName, String key){
        final String[][] msg = new String[1][1];
        final boolean[] isCmdRunSucFlag = {false};
        final Semaphore semaphore = new Semaphore(0);

        final String appidStr = new String(msgCrypt.getAppId());
        final String deviceIdStr = StringTool.byteHexToSting(msgCrypt.getDeviceId());
        final String the_license = License;
        final String the_deviceName = deviceName;
        final String serc = key;

        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = "https://admin.dkcloudid.cn/api/regDev";
                JSONObject postData = new JSONObject();
                JSONObject data = new JSONObject();
                MediaType JSON = MediaType.parse("application/json;charset=utf-8");//数据类型为json格式，
                try {
                    data.put("devId", deviceIdStr);
                    data.put("code", the_license);
                    data.put("name", the_deviceName);

                    String timeStr = String.valueOf(getCurrentTimestamp());
                    String signStr = md5(appidStr + serc + data.toString() + timeStr);

                    postData.put("data", data.toString());
                    postData.put("appid", appidStr);
                    postData.put("sign", signStr);
                    postData.put("timestamp", timeStr);

                    DKLog.d(TAG, "postData:" + postData.toString());
                    DKLog.d(TAG, "data:" + data.toString());

                    OkHttpClient client = new OkHttpClient();
                    RequestBody body = RequestBody.create(JSON, String.valueOf(postData));
                    Request request = new Request.Builder()
                            .url(url)
                            .post(body)
                            .build();
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            String res = response.body().string();
                            DKLog.d(TAG, "POST成功:" + res);
                            if (res.contains("成功")) {
                                isCmdRunSucFlag[0] = true;
                            }
                            else {
                                err_msg = res;
                                isCmdRunSucFlag[0] = false;
                            }
                            semaphore.release();
                        }

                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            DKLog.e(TAG, "请检查网络！");
                            err_msg = "请检查网络";
                            isCmdRunSucFlag[0] = false;
                            semaphore.release();
                        }
                    });
                    DKLog.d(TAG, postData.toString());
                } catch (JSONException e) {
                    DKLog.e(TAG, e.getMessage());
                    DKLog.e(TAG, e.getStackTrace());
                }
            }
        }).start();

        try {
            semaphore.tryAcquire(TIME_OUT_MS, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            DKLog.e(TAG, e.getMessage());
            DKLog.e(TAG, e.getStackTrace());
            err_msg = "请求超时";
        }

        return isCmdRunSucFlag[0];
    }

    /**
     * 获取错误信息
     * @return 错误信息，无错误返回null
     */
    public String getErrMsg() {
        return err_msg;
    }

    // 单位秒：
    public long getCurrentTimestamp() {
        return System.currentTimeMillis() / 1000;
    }

    //md5加密的方法小写
    public  String md5(String plainText) {
        DKLog.e(TAG, plainText);

        //定义一个字节数组
        byte[] secretBytes = null;
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            //对字符串进行加密
            md.update(plainText.getBytes());
            //获得加密后的数据
            secretBytes = md.digest();
        } catch (NoSuchAlgorithmException e) {
            DKLog.e(TAG, e.getMessage());
            DKLog.e(TAG, e.getStackTrace());
        }
        //将加密后的数据转换为16进制数字
        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
        // 如果生成数字未满32位，需要前面补0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }
}
